<template>
  <n-space class="work" vertical>
    <n-space justify="space-between">
      <n-button @click="createWork"> 添加作品 </n-button>
    </n-space>
    <n-data-table :columns="columns" :data="data" :bordered="false" />
  </n-space>
  <n-drawer v-model:show="active" width="50%">
    <n-drawer-content :title="updateId ? '添加作品' : '编辑作品'">
      <n-form
        ref="formRef"
        :label-width="80"
        label-placement="left"
        :model="formValue"
        :rules="rules"
      >
        <n-form-item label="作品名" path="name">
          <n-input v-model:value="formValue.name" placeholder="作品名" />
        </n-form-item>
        <n-form-item label="描述" path="desc">
          <n-input v-model:value="formValue.desc" placeholder="描述" />
        </n-form-item>
        <n-form-item label="优先级" path="priority">
          <n-input-number v-model:value="formValue.priority" clearable />
        </n-form-item>
        <n-form-item label="链接地址" path="linkUrl">
          <n-input v-model:value="formValue.linkUrl" placeholder="链接地址" />
        </n-form-item>
        <n-form-item label="源码链接" path="sourceUrl">
          <n-input v-model:value="formValue.sourceUrl" placeholder="源码链接" />
        </n-form-item>
        <n-form-item label="封面地址" path="imgUrl">
          <Upload v-model:fileUrl="formValue.imgUrl" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-button attr-type="button" @click="handleValidateClick">
          保存
        </n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang="ts">
import {
  type FormInst,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSpace,
  NDataTable,
  NDrawer,
  NDrawerContent,
  NInputNumber,
  NImage,
  type DataTableColumns,
  type UploadFileInfo,
} from "naive-ui";
import {
  type work,
  type createWork as createWorkInter,
  create as apiCreateWork,
  findAll as apiFindAllWork,
  update as apiUpdateWork,
  deleteWork as apiDeleteWork,
} from "~/api/work";
import { uploadPostCoverUrl as uploadPostCoverUrl } from "../../api/file";

useHead({
  title: '作品管理',//网站标题
})

definePageMeta({
  title: "作品管理",
});
const active = ref(false);
const updateId = ref("");
const formValue = ref<createWorkInter>({
  imgUrl: "",
  name: "",
  desc: "",
  priority: 0,
  linkUrl: "",
  sourceUrl: "",
});
const createWork = async () => {
  active.value = true;
  updateId.value = "";
  formValue.value = {
    imgUrl: "",
    name: "",
    desc: "",
    priority: 0,
    linkUrl: "",
    sourceUrl: "",
  };
};

const createColumns = ({
  del,
  edit,
}: {
  del: (row: work) => void;
  edit: (row: work) => void;
}): DataTableColumns<work> => {
  return [
    {
      title: "作品名",
      key: "name",
    },
    {
      title: "优先级",
      key: "priority",
    },
    {
      title: "描述",
      key: "desc",
    },
    {
      title: "访问地址",
      key: "linkUrl",
    },
    {
      title: "封面",
      key: "imgUrl",
      render(row: work) {
        return h(
          NImage,
          {
            width: 100,
            src: row.imgUrl,
          },
          {}
        );
      },
    },
    {
      title: "",
      key: "actions",
      render(row: work) {
        return [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              style: {
                "margin-right": "10px",
              },
              onClick: () => edit(row),
            },
            { default: () => "编辑" }
          ),
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              style: {
                "margin-right": "10px",
              },
              onClick: () => del(row),
            },
            { default: () => "删除" }
          ),
        ];
      },
    },
  ];
};

const data = ref<work[]>([]);

const columns = createColumns({
  async del(row: work) {
    const res = await apiDeleteWork(row.id);
    if (res.code === 0) {
      naiveui.message.success("删除成功");
      findWork();
    }
  },
  edit(row: work) {
    active.value = true;
    updateId.value = row.id;
    formValue.value = { ...row };
  },
});

const rules = {
  name: {
    required: true,
    message: "请输入作品名",
    trigger: ["input"],
  },
  linkUrl: {
    required: true,
    message: "请输入链接地址",
    trigger: ["input"],
  },
  desc: {
    pattern: /^.{0,100}$/,
    message: "长度0到100",
    trigger: ["input"],
  },
};

const formRef = ref<FormInst | null>(null);
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      if (updateId.value) {
        const res = await apiUpdateWork(updateId.value, formValue.value);
        if (res.code === 0) {
          findWork();
          naiveui.message.success("修改成功");
        }
      } else {
        await apiCreateWork(formValue.value);
      }
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
  });
};

const findWork = async () => {
  
  const res = await apiFindAllWork();
  if (res.data) {
    data.value = res.data;
  }
};
onMounted(async () => {
  findWork();
});
</script>
<style lang="scss" scoped>
.work {
  
  padding: 20px 15px;
  .n-input,
  .n-select {
    width: 200px;
  }
}
.n-form {
  display: flex;
  flex-wrap: wrap;
  .n-form-item {
    width: 48%;
  }
}
</style>
